<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    #box {
      width: 200px;
      height: 200px;
      border: 1px solid #000;
    }
  </style>
</head>

<body>
  <input id="input" type="text" name="" placeholder="输入要发送的信息">
  <button id="btn">发送</button>
  <div id="box"></div>
</body>

<script>
  const div = document.querySelector('#box')
  const input = document.querySelector('#input');
  const button = document.querySelector('#btn');

  var ws = new WebSocket('ws://localhost:8080');
  ws.addEventListener('open', function () {
    div.innerHTML = '连接服务成功了'
  })

  ws.addEventListener('close', function () {
    div.innerHTML = '服务已经断开'
  })

  ws.addEventListener('error', function () {
    console.log('服务器异常')
  })

  button.addEventListener('click', function () {
    var value = input.value;
    ws.send(value);
    input.value=''
  })

  ws.addEventListener('message', e => {
    let dv=document.createElement('div')
    dv.innerText=`${e.data}`
    box.append(dv)
  })
</script>

</html>